package com.sk.weichat.view.chatHolder;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.IsBindAlipayBean;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.redpacket.EventRedReceivedStatus;
import com.sk.weichat.bean.redpacket.RedpacketDetailBean;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.me.redpacket.RedpacketRouter;
import com.sk.weichat.ui.me.redpacket.SendRedPacketActivity1;
import com.sk.weichat.ui.me.wallet.IdentityAuthenticationActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.util.HtmlUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.NoDoubleClickListener;
import com.sk.weichat.view.redDialog.RedDialog;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

class RedViewHolder extends AChatHolderInterface {

    TextView mTvContent;
    TextView mTvType;
    ImageView iv_image;
    private TextView tv_redpacket_status;

    boolean isKeyRed;
    private RedDialog mRedDialog;
    private RedpacketDetailBean mRedpacketDetailBean;

    public RedViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    @Override
    public int itemLayoutId(boolean isMysend) {
        return isMysend ? R.layout.chat_from_item_redpacket : R.layout.chat_to_item_redpacket;
    }

    @Override
    public void initView(View view) {
        mTvContent = view.findViewById(R.id.chat_text);
        mTvType = view.findViewById(R.id.tv_type);
        mRootView = view.findViewById(R.id.chat_warp_view);
        iv_image = view.findViewById(R.id.iv_image);
        tv_redpacket_status = view.findViewById(R.id.tv_redpacket_status);
    }

    @Override
    public void fillData(ChatMessage message) {
        //0：未领取 1 ：已领取 2：已领完 -1：已退款 （已过期）4 已过期
        switch (mdata.getFileSize()) {
            case 0:
                if (isMysend) {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_red);
                } else {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_red1);
                }
                iv_image.setBackgroundResource(R.mipmap.img_redpaper_normal);

                tv_redpacket_status.setVisibility(View.GONE);
                break;
            case 1:
                if (isMysend) {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red);
                } else {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red1);
                }
                iv_image.setBackgroundResource(R.mipmap.img_redpaper_open);
                tv_redpacket_status.setVisibility(View.VISIBLE);
                tv_redpacket_status.setText("红包已领取");
                break;
            case 2:
                if (isMysend){
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red);
                    if (isGounp){
                        tv_redpacket_status.setText("红包已抢光");
                    }else {
                        tv_redpacket_status.setText("红包已领取");
                    }
                    iv_image.setBackgroundResource(R.mipmap.img_redpaper_open);
                }else {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red1);
                    tv_redpacket_status.setText("红包已抢光");
                    iv_image.setBackgroundResource(R.mipmap.img_redpaper_normal);
                }
                tv_redpacket_status.setVisibility(View.VISIBLE);
                break;
            case -1:
            case 4:
                if (isMysend){
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red);
                }else {
                    mRootView.setBackgroundResource(R.drawable.a_bg_for_chat_light_red1);
                }
                iv_image.setBackgroundResource(R.mipmap.img_redpaper_normal);
                tv_redpacket_status.setVisibility(View.VISIBLE);
                tv_redpacket_status.setText("红包已过期");
                break;

        }
        String s = StringUtils.replaceSpecialChar(message.getContent());
        CharSequence charSequence = HtmlUtils.transform200SpanString(s.replaceAll("\n", "\r\n"), true);
        mTvContent.setText(charSequence);

        isKeyRed = "3".equals(message.getFilePath());
        mTvType.setText(getString(isKeyRed ? R.string.chat_kl_red : R.string.chat_red));

        mRootView.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                RedViewHolder.super.onClick(view);
            }
        });
    }

    @Override
    public boolean isOnClick() {
        return false; // 红包消息点击后回去请求接口，所以要做一个多重点击替换
    }

    @Override
    protected void onRootClick(View v) {
        //判断 如果该条红包消息 是正在发送中  则不可点击领取红包
        if (mdata.getMessageState()== ChatMessageListener.MESSAGE_SEND_ING){
            return;
        }
        clickRedpacket();
    }


    // 点击红包 查询红包状态
    public void clickRedpacket() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(mContext);
        }
        final String token = CoreManager.requireSelfStatus(mContext).accessToken;
        final String redId = mdata.getObjectId();
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", token);
        params.put("id", redId);
        HttpUtils.post().url(CoreManager.requireConfig(mContext).RED_PACKET_STATUS)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {

                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        DialogHelper.dismissProgressDialog();

                        if (result.getResultCode() == 1) {
                            if (result.getData() != null) {
                                // 当resultCode==1时，表示可领取
                                // 当resultCode==0时，表示红包已过期、红包已退回、红包已领完
                                mRedpacketDetailBean = result.getData();
                                if (mRedpacketDetailBean.getStatus() == 0) {//未领取  判断是否绑定支付宝
                                    isBindAlipay();
                                } else {
                                    RedpacketRouter.route(mContext, CoreManager.getSelf(mContext).getUserId(), mdata.getPacketId(), mRedpacketDetailBean);
                                }
                                EventBus.getDefault().post(new EventRedReceivedStatus(mdata.getPacketId(), mRedpacketDetailBean.getStatus()));
                            }
                        } else {
                            DialogHelper.dismissProgressDialog();
                            Toast.makeText(mContext, result.getResultMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }
    /**
     * @author: czl
     * @description 是否绑定支付宝
     * @date: 2019/10/9 11:10
     */
    public void isBindAlipay() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", CoreManager.getSelfStatus(mContext).accessToken);
        HttpUtils.post().url(CoreManager.getConfig(mContext).IS_BIND_ALIPAY)
                .params(params)
                .build()
                .execute(new BaseCallback<IsBindAlipayBean>(IsBindAlipayBean.class) {
                    @Override
                    public void onResponse(ObjectResult<IsBindAlipayBean> result) {
                        if (result.getResultCode() == 1) {
                            IsBindAlipayBean mIsBindAlipayBean = result.getData();
                            if (mIsBindAlipayBean.getState().equals("BINDING")) {//已绑定支付宝 打开红包
                                RedpacketRouter.route(mContext, CoreManager.getSelf(mContext).getUserId(), mdata.getPacketId(), mRedpacketDetailBean);
                            } else {//没绑定支付宝 跳转至绑定支付宝页面
                                ToastUtil.showToast(mContext,"绑定支付宝才能正常收取红包");
                                mContext.startActivity(new Intent(mContext, IdentityAuthenticationActivity.class)
                                        .putExtra("aliPayNickName", "").putExtra("isReceiveRedpack", true).putExtra("ChatMessage", mdata));
                            }
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showToast(mContext, e.toString());
                    }
                });
    }
    // 打开红包
  /*  public void openRedPacket(final String token, String redId) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", token);
        params.put("id", redId);

        HttpUtils.get().url(CoreManager.requireConfig(mContext).REDPACKET_OPEN)
                .params(params)
                .build()
                .execute(new BaseCallback<OpenRedpacket>(OpenRedpacket.class) {

                    @Override
                    public void onResponse(ObjectResult<OpenRedpacket> result) {
                        if (mRedDialog != null) {
                            mRedDialog.dismiss();
                        }
                        if (result.getData() != null) {
                            mdata.setFileSize(2);
                            ChatMessageDao.getInstance().updateChatMessageReceiptStatus(mLoginUserid, mToUserId, mdata.getPacketId());
                            fillData(mdata);

                            OpenRedpacket openRedpacket = result.getData();
                            Bundle bundle = new Bundle();
                            Intent intent = new Intent(mContext, MucRedPacketDetailsActivity.class);
                            bundle.putSerializable("openRedpacket", openRedpacket);
                            bundle.putInt("redAction", 1);
                            bundle.putInt("timeOut", 0);

                            bundle.putBoolean("isGroup", isGounp);
                            bundle.putString("mToUserId", mToUserId);
                            intent.putExtras(bundle);
                            mContext.startActivity(intent);
                            // 更新余额
                            CoreManager.updateMyBalance();

                            EventBus.getDefault().post(new EventRedReceived(openRedpacket));
                        } else {
                            Toast.makeText(mContext, result.getResultMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (mRedDialog != null) {
                            mRedDialog.dismiss();
                        }
                    }
                });
    }*/

    // 通知更新输入框
    private void changeBottomViewInputText(String text) {
        mHolderListener.onChangeInputText(text);
    }

    @Override
    public boolean enableSendRead() {
        return true;
    }
}
